#!/usr/bin/env python
#coding=utf-8

from oss.oss_api import *
from oss.oss_util import *
from oss.oss_xml_handler import *
import datetime
import os, sys, re, time
import string
from Tkinter import *   #引入Tkinter工具包
import tkMessageBox

HOST="oss.aliyuncs.com"
ACCESS_ID="OoAHaZIRoZqkbleI"
SECRET_ACCESS_KEY="JhQfARQphr7bUCUNSJAKd8nz3nCTAF"

def format_datetime(osstimestamp):
    date = re.compile("(\.\d*)?Z").sub(".000Z", osstimestamp)
    ts = time.strptime(date, "%Y-%m-%dT%H:%M:%S.000Z")
    return time.strftime("%Y-%m-%d %H:%M", ts)
    
def get_oss(show_bar = True):
    oss = OssAPI(HOST, ACCESS_ID, SECRET_ACCESS_KEY)
    oss.show_bar = show_bar 
    return oss
#root.grid_slaves(0,1)[0].get('1.0','1.end')

def cmd_getallbucket():
    res = get_oss().get_service()
    if (res.status / 100) == 2:
        body = res.read()
        h = GetServiceXml(body)
        root.grid_slaves(2,0)[0].delete(0) #重复执行时先删除原来的Bucket
        for i in h.list():
            if len(i) == 2:
                root.grid_slaves(2,0)[0].insert(END,i[0])
                outputlog('GET Bucket %s ,create by %s' %(i[0],format_datetime(i[1])))
    return res
    
def loginOSS():
    #ACCESS_ID=root.grid_slaves(0,1)[0].get('1.0','1.end')
    #SECRET_ACCESS_KEY=root.grid_slaves(0,3)[0].get('1.0','1.end')
    cmd_getallbucket()
 
def bucketlist(event):
    print dir(event)
    
def tkmsg():
    tkMessageBox.showinfo("Info",dir(root))
    
def outputlog(item):
    root.grid_slaves(8,0)[0].insert(0,item)
    
if __name__=="__main__":
    root = Tk()  #初始化Tk
    root.title("OSS File Tools  [VNSOFT v0.1]")
    #root.resizable(False)
    Label(root,text="ACCESS ID:").grid(row=0,column=0) #创建一个label标签
    Entry(root,width=15).grid(row=0,column=1)
    Label(root,text="SECRET ACCESS KEY:").grid(row=0,column=2) #创建一个label标签
    Entry(root,width=30).grid(row=0,column=3)
    Button(root,text="LOGIN",command=loginOSS).grid(row=0,column=4,sticky =NSEW)
    
    Label(root,text='Buckets:').grid(row=1,column=0,sticky=W)
    lb1 = Listbox(root)
    lb1.grid(row=2,column=0,rowspan=3,padx=2,pady=2)
    lb1.bind("<Double-Button-1>",bucketlist)
    Listbox(root).grid(row=2,column=1,rowspan=3,columnspan=3,sticky =NSEW,padx=2,pady=2)
    Button(root,text='下载').grid(row=3,column=4,sticky =EW)
    Button(root,text='修改HTTP HEAD').grid(row=4,column=4,sticky =EW)
    
    Label(root,text='Drives:').grid(row=5,column=0,sticky=W)
    Listbox(root).grid(row=6,column=0,padx=2,pady=2)
    Listbox(root).grid(row=6,column=1,columnspan=3,sticky =NSEW,padx=2,pady=2)
    Button(root,text='上传').grid(row=6,column=4,sticky =EW)
    Label(root,text='Output Log').grid(row=7,column=0,sticky=W)
    Listbox(root).grid(row=8,column=0,columnspan=5,sticky=NSEW,padx=2,pady=2)
    root.mainloop()  #进入消息循环